<template>
  <div class="login_body">
    <div class="bg" />
    <div class="box">
      <div class="title">智慧园区-登录</div>
      <el-form ref="form" :model="formData" :rules="rules">
        <el-form-item label="账号" prop="username">
          <el-input v-model="formData.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" type="password" />
        </el-form-item>
        <el-form-item prop="remember">
          <el-checkbox v-model="formData.remember">记住我</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login_btn" @click="doLogin()">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { loginAPI } from '@/apis/user';
import { FORMDATA_KEY } from '@/constants';
import { onMounted } from 'vue';
import router from '@/router';
import { useUserStore } from '@/stores/user';
import { setToken } from '@/utils/auth';
const store = useUserStore
// ref创建响应式数据
// 1. 数据
const formData = ref({
  username: 'demo',
  password: 'Hmzs%001',
  remember: ''
})
// 2. 校验规则
const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}
// 3. 登录
const form = ref<FormInstance | undefined>()
const doLogin = () => {
  form.value!.validate(async (valid) => {
    if (valid) {
      const { username, password } = formData.value
      const res = await loginAPI({ username, password })
      // 确保登录流程ok后，并且账号密码正确的
      if (formData.value.remember) {
        localStorage.setItem(FORMDATA_KEY, JSON.stringify(formData.value))
      } else {
        localStorage.removeItem(FORMDATA_KEY)
      }
      const store = useUserStore()
      store.setToken(res.data.token)
      router.replace('/')
      console.log(res.data);
    }
  })
}
// 从本地取出数据赋值 
onMounted(() => {
  const jsonStr = localStorage.getItem(FORMDATA_KEY)
  if (jsonStr !== null) {
    const userPassObj = JSON.parse(jsonStr)
    if (userPassObj) {
      formData.value = userPassObj
    }
  }
})

</script>